<?php

namespace common\observer;


use common\service\EntityService;
use support\SingletonTrait;
use common\service\MessageService;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;
use think\Hook;

/**
 * 实体属性发生变化 制片小助手通知到相关人员
 */
class AttrChangeSendProducerAssistantMessage implements SplObserver
{
    use SingletonTrait;

    // 监听的模块
    private $listenModule = ['asset'];
    // 监听的字段
    private $listenAttrFields = [
        'asset_perform_species'
    ];
    // 字段中文名
    private $attrFieldsLabel = [
        'asset_perform_species' => '角色类型'
    ];

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        try {
            $entity = $subject->getSubjectData();
            $updateEntityData = $subject->getSplUpdateData();

            $entityModuleCode = module_by_id($entity['module_id'])['code'];
            if (!in_array($entityModuleCode, $this->listenModule)) {
                return;
            }
            $changeListenKeys = array_intersect(array_keys($updateEntityData), $this->listenAttrFields);
            if (empty($changeListenKeys)) {
                return;
            }

            $oldData = $subject->getSplOldData();
            $oldJsonFields = json_decode($oldData['json'] ?? '{}', true);
            $oldData = array_merge($oldData, $oldJsonFields);

            // 拼接提示语
            $noteText = '【' . $entity['initial_episode_code'] . '/' . $entity['showings_number'] . '/' . $entity['name'] . '】的';
            foreach ($changeListenKeys as $changeListenKey) {
                $old = $oldData[$changeListenKey] ?? '空';
                $new = $updateEntityData[$changeListenKey];
                if (is_array($new)) {
                    $new = serialize($new);
                }
                $label = $this->attrFieldsLabel[$changeListenKey];
                $noteText .= $label . '由' . $old . '变更为' . $new . ' ';
            }
            $hookData = [
                'type' => 'entity_attribute_change',
                'data' => [
                    'entity' => $entity,
                    'entity_module_code' => $entityModuleCode,
                    'note_text' => $noteText,
                ],
            ];
            Hook::listen('entity_change_after', $hookData);

        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
